<?php

namespace App\Morefun\Wechat;

use App\Entities\WechatConfig;
use EasyWeChat\Foundation\Application;
use Exception;
use Illuminate\Container\Container;
use Doctrine\Common\Cache\PredisCache;

class AppMaker
{
    private $apps = [];

    /**
     * @param $groupCode
     * @return Application
     * @throws Exception
     */
    public function makeByGroupCode($groupCode)
    {
        if (isset($this->apps[$groupCode])) {
            return $this->apps[$groupCode];
        }

        $config = WechatConfig::query()->where('group_code', $groupCode)->first();

        if (null === $config) {
            throw new Exception("Error group_code:{$groupCode}");
        }

        $app = new Application([
            'debug' => config('app.debug'),
            'app_id' => $config->getAttribute('app_id'),
            'secret' => $config->getAttribute('app_secret'),
        ]);

        $client = Container::getInstance()->make('redis')->connection()->client();
        $app->offsetSet('cache', new PredisCache($client));

        $this->apps[$groupCode] = $app;

        return $app;
    }
}
